//
//  WBWelcomeView.swift
//  WeiBoApp
//
//  Created by CrazyHacker on 16/7/4.
//  Copyright © 2016年 CrazyHacker. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

class WBWelcomeView: UIView {
    
    @IBOutlet weak var iconView: UIImageView!
    
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var iconViewBottomCons: NSLayoutConstraint!
    
    @IBOutlet weak var iconWithCons: NSLayoutConstraint!
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
       guard let urlString = WebNetworkTools.shared.userAccount.screen_name,
        iconImageName = WebNetworkTools.shared.userAccount.avatar_large else {
            return
        }
        
        let url = URL(string: iconImageName)
        iconView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big"))
        userNameLabel.text = "欢迎 \(urlString) 归来!"
        
        // 由于此时iconView的尺寸尚未就位,为0, 所以取其宽度约束的值
        iconView.layer.cornerRadius = iconWithCons.constant * 0.5
        iconView.layer.masksToBounds = true
        
    }
    
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        self.layoutIfNeeded()
        
        iconViewBottomCons.constant = -bounds.size.height + 100
        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {
            self.layoutIfNeeded()
            
            }) { (_) in
               UIView.animate(withDuration: 1.3, animations: {
                self.userNameLabel.alpha = 1
                
                }, completion: { (_) in
                    self.removeFromSuperview()
               })
        }
    
    }
    
}

extension WBWelcomeView {
   class func welcomeView()->WBWelcomeView {
        let nib = UINib(nibName: "WBWelcomeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomeView
        v.frame = UIScreen.main().bounds
        return v
    }
}
